package com.ruoyi.wx.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.doudian.utils.Http;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.wx.pojo.vo.QRCodeVO;
import com.ruoyi.wx.service.WxAuthService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.utils.WeiXinUtil.httpRequest;


/**
 * @author X
 * @version 1.0
 * @ClassName WXController
 * @description 微信数据控制器
 * @date 2020/11/6
 **/
@RestController
@RequestMapping("/weixin")
@CrossOrigin
@Api(tags = "二维码")
@Slf4j
public class WXController {

    @Autowired
    private WxAuthService wxAuthService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;

    // 获取Ticket
    public final static String ticket_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    //获取二维码
    public final static String erweima = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";

    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx50b8f1d6623c060d&secret=dfe5dc0ce5374135bdcdb4f4ba9bbc19";

    /**
     * 通过商户id获取ticket,返回二维码url
     *
     * @param type 1_1 [第一个1：商户id  第二个1：代表关注二维码,2:代表核销二维码]
     * @return
     */

    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1_1 [第一个1：商户id  第二个1：代表关注二维码,2:代表核销二维码]", required = false, dataType = "String", paramType = "path", example = "blues")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "接口返回成功状态"),
            @ApiResponse(code = -1, message = "接口返回失败状态")
    })
    @ApiOperation(value = "通过商户id获取ticket,返回二维码url", notes = "")
    @PostMapping("/getTicket/{scene_str}")
    public AjaxResult getTicket(
            @PathVariable(value = "scene_str") String type) {
        /* Map<String, Object> map = AccessTokenCache.getInstance().getAcessTokenAndExpiresIn("wx50b8f1d6623c060d", "dfe5dc0ce5374135bdcdb4f4ba9bbc19");*/
        String accessToken = wxAuthService.adminGetAccessToken();
//        String accessToken = (String) map.get("access_token");
        //body
        String uu = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\":" + "\"" + type + "\"}}}";
        System.out.println(uu);
        JSONObject jsonObject = httpRequest(ticket_url + accessToken, "POST", uu);
        String jsonString = JSON.toJSONString(jsonObject);
        Map parseObject = JSON.parseObject(jsonString, Map.class);
        Object errcode = parseObject.get("errcode");
        if (ObjectUtil.isNotNull(errcode)) {
            return AjaxResult.error("刷新页面重新登录");
        }
        String ticket = (String) parseObject.get("ticket");
        String url = (String) parseObject.get("url");
        String ss = erweima + ticket;
        QRCodeVO qrCodeVO = new QRCodeVO();
        qrCodeVO.setTicket(ss);
        qrCodeVO.setUrl(url);
        //二维码
        return AjaxResult.success(qrCodeVO);
    }

    /***
     * 获取用户ID
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/getUserId")
    public AjaxResult getUserId(HttpServletRequest httpServletRequest) {
        String token = tokenService.getToken(httpServletRequest);
        Claims claims = tokenService.parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = tokenService.getTokenKey(uuid);
        // 获取到用户信息
        LoginUser loginUser = redisCache.getCacheObject(userKey);
        //获取用id
        Long userId = loginUser.getUser().getUserId();
        return AjaxResult.success("userId", userId);
    }
}